package xyz.xiaomuyu.moment_read_app.ui.login;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import xyz.xiaomuyu.moment_read_app.MyTabbar;
import xyz.xiaomuyu.moment_read_app.R;
import xyz.xiaomuyu.moment_read_app.bean.woshishabi;
import xyz.xiaomuyu.moment_read_app.util.DBUtil;

public class LoginActivity extends AppCompatActivity {
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private EditText accountEdit;
    private EditText passwordEdit;
    private Button loginButton;
    private CheckBox rememberPassword;
    private ProgressDialog loginDialog;
    private String userName;
    private String password;
    private String headId;
    private int userId;

    private static final int LOGIN_SUCCESS = 101;
    private static final int LOGIN_FAILED = 102;
    /**
     * 设置handler接收网络线程的信号并处理
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOGIN_SUCCESS:
                    loginDialog.cancel();
                    Toast.makeText(getApplicationContext(), "登录成功！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LoginActivity.this, MyTabbar.class);
                    intent.putExtra("userId", userId);
                    intent.putExtra("userName", userName);
                    intent.putExtra("headId",headId);
                    woshishabi.userName = new String(userName);
//                    将用户id username 存储
                    @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = getSharedPreferences("userAccount", MODE_PRIVATE).edit();
                    editor.putInt("userId", userId);
                    editor.putString("userName", userName);
                    editor.apply();
                    startActivity(intent);
                    finish();
                    break;
                case LOGIN_FAILED:
                    Toast.makeText(getApplicationContext(), "用户名或密码错误，登录失败！", Toast.LENGTH_SHORT).show();
                    loginDialog.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
//        ImmersionBar.with(this)
//                .init();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        //记住密码功能
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        accountEdit = findViewById(R.id.ht_username);
        passwordEdit = findViewById(R.id.ht_password);
        rememberPassword = findViewById(R.id.remember_password);
        boolean isRemember = pref.getBoolean("remember_password", false);
        if (isRemember) {
            //将账号和密码都设置到文本框中
            String account = pref.getString("account", "");
            String password = pref.getString("password", "");
            accountEdit.setText(account);
            passwordEdit.setText(password);
            rememberPassword.setChecked(true);
        }

        /**
         * 没有账号，跳转到注册页面
         */
        TextView textView = (TextView) findViewById(R.id.login_to_register);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        /**
         * 响应登录按钮，实现登录功能
         * 同时使用 SharedPreference 存储，实现 “记住密码” 功能
         */
        loginButton = (Button) findViewById(R.id.login_to_homepage);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = pref.edit();
                if (rememberPassword.isChecked()) {
                    userName = accountEdit.getText().toString();
                    password = passwordEdit.getText().toString();
//                    System.out.println("正在存储您的数据,存储的数据为："+userName+"和"+password);
                    editor.putBoolean("remember_password", true);
                    editor.putString("account", userName);
                    editor.putString("password", password);
                } else {
                    editor.clear();
                }
                editor.apply();
                if (!judgeInfo()) {
                    Toast.makeText(getApplicationContext(), "信息不全，请先补充信息", Toast.LENGTH_LONG).show();
                } else {
                    login();
                }
            }
        });
    }

    /**
     * 检查 username password是否填写完成
     *
     * @return
     */
    public boolean judgeInfo() {
        userName = accountEdit.getText().toString().trim();
        password = passwordEdit.getText().toString().trim();
        // 若两者有任何一个没有填信息，就是错误
        return !TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password);
    }

    public void login() {
        /*
        设置登录等待框
         */
        loginDialog = new ProgressDialog(LoginActivity.this);
        loginDialog.setCanceledOnTouchOutside(false);
        loginDialog.setMessage("正在登录...");
        loginDialog.show();

        /*
        建立网络线程进行登录检查
         */
        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //线程间的沟通准备
                Message message = new Message();
                try {
                    Connection connection = DBUtil.getConn();
                    String sql = "select * from user where user_name = '" + userName + "' and password = '" + password + "'";
                    Statement statement = connection.createStatement();
                    ResultSet resultSet = statement.executeQuery(sql);

                    //处理返回回来的数据
                    if (!resultSet.next()) {
                        message.what = LOGIN_FAILED;
                    } else {
                        userId = resultSet.getInt("user_id");
                        userName = resultSet.getString("user_name");
                        headId = resultSet.getString("head_id");
                        System.out.println(userId);
                        message.what = LOGIN_SUCCESS;
                    }
                    handler.sendMessage(message);

                    resultSet.close();
                    statement.close();
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}